package org.sao.geteway.componet.fallback;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.sao.common.constant.ServiceNameConstant;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * @author zhangyang
 *
 */


@Slf4j
@Component
public class AdminFallbackProvider implements  FallbackProvider{
	
	
	private static final String ADMIN_SERVICE_DISABLE = "权限管理模块不可用";


	@Override
	public ClientHttpResponse fallbackResponse(Throwable cause) {
		// TODO Auto-generated method stub
		return new ClientHttpResponse() {

			@Override
			public InputStream getBody() throws IOException {
				// TODO Auto-generated method stub
				 if (cause != null && cause.getMessage() != null) {
	                    log.error("调用:{} 异常：{}", getRoute(), cause.getMessage());
	                    return new ByteArrayInputStream(cause.getMessage().getBytes());
	                } else {
	                    log.error("调用:{} 异常：{}", getRoute(), ADMIN_SERVICE_DISABLE);
	                    return new ByteArrayInputStream(ADMIN_SERVICE_DISABLE.getBytes());
	                }
			}

			@Override
			public HttpHeaders getHeaders() {
				// TODO Auto-generated method stub
				HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
			}

			@Override
			public HttpStatus getStatusCode() throws IOException {
				// TODO Auto-generated method stub
				 return HttpStatus.SERVICE_UNAVAILABLE;
			}

			@Override
			public int getRawStatusCode() throws IOException {
				// TODO Auto-generated method stub
				return HttpStatus.SERVICE_UNAVAILABLE.value();
			}

			@Override
			public String getStatusText() throws IOException {
				// TODO Auto-generated method stub
				return HttpStatus.SERVICE_UNAVAILABLE.getReasonPhrase();
			}

			@Override
			public void close() {
				// TODO Auto-generated method stub
				
			}
			
		};
	}
	
	
	
	
	@Override
	public ClientHttpResponse fallbackResponse() {
		// TODO Auto-generated method stub
		  return fallbackResponse(null);
	}

	@Override
	public String getRoute() {
		// TODO Auto-generated method stub
		return ServiceNameConstant.ADMIN_SERVICE;
	}


}
